﻿Public Class frmHistory

    Protected dtData As New DataTable
    Protected m_cData As New clsDbCondData

    Private fileName As String = ""
    Private fileSaveTitle As String = ""
    Private serchMaxCount As Integer = 1000

    Dim FromDate As Date
    Dim ToDate As Date
    Dim procFrom As Integer
    Dim procTo As Integer
    Dim isSerchResult As Boolean = False


    Private Sub frmSeach_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'タイトル変更
        Me.Text = "履历检索画面" 'UPD MIAO 2018/8/7

        'コンボボックスの選択肢設定
        createComboBox()

        'コンボボックス作成後にイベントを設定
        AddHandler cmbProcCode.SelectedIndexChanged, AddressOf cmbProcCode_SelectChanged
        AddHandler cmbProcCode.TextChanged, AddressOf cmbProcCode_TextChanged

        AddHandler cmbProcCodeFrom.TextChanged, AddressOf cmbProcCodeFromTo_SelectChanged
        AddHandler cmbProcCodeFrom.TextChanged, AddressOf cmbProcCodeFromTo_TextChanged
        AddHandler cmbProcCodeTo.TextChanged, AddressOf cmbProcCodeFromTo_SelectChanged
        AddHandler cmbProcCodeTo.TextChanged, AddressOf cmbProcCodeFromTo_TextChanged

        '最大取得件数設定
        getSerchMaxCount()

        'DataGridViewの設定
        settingGridView()

        isSerchResult = False

    End Sub

    '検索ボタン押下処理
    Private Sub btnManufComp_Click(sender As Object, e As EventArgs) Handles btnSerch.Click

        '検索結果欄初期化
        DataGridView1.DataSource = Nothing
        isSerchResult = False
        '検索件数初期化
        txtRowCount.Text = ""

        '入力チェック
        If inputCheck() Then
            Exit Sub
        End If

        '検索処理
        serch()

    End Sub

    '組立ロットNo入力処理
    Private Sub txtKeyNo_TextChanged(sender As Object, e As EventArgs) Handles txtKeyNo.TextChanged
        If String.IsNullOrEmpty(txtKeyNo.Text) Then
            '値なしの場合は工程を有効化
            txtWaferLotno.Enabled = True
            txtWaferLotno.BackColor = System.Drawing.Color.LightCyan
        Else
            '値ありの場合は工程を無効化
            txtWaferLotno.Text = String.Empty
            txtWaferLotno.Enabled = False
            txtWaferLotno.BackColor = SystemColors.Control
        End If
    End Sub

    'GroupKeyNo入力処理
    Private Sub txtWaferLotno_TextChanged(sender As Object, e As EventArgs) Handles txtWaferLotno.TextChanged
        If String.IsNullOrEmpty(txtWaferLotno.Text) Then
            '値なしの場合は工程を有効化
            txtKeyNo.Enabled = True
            txtKeyNo.BackColor = System.Drawing.Color.LightCyan
        Else
            '値ありの場合は工程を無効化
            txtKeyNo.Text = String.Empty
            txtKeyNo.Enabled = False
            txtKeyNo.BackColor = SystemColors.Control
        End If
    End Sub

    '工程入力処理手入力対応
    Private Sub cmbProcCode_TextChanged(sender As Object, e As EventArgs)
        If String.IsNullOrEmpty(cmbProcCode.Text) Then
            '値なしの場合は工程（From,To）を有効化
            cmbProcCodeFrom.Enabled = True
            cmbProcCodeTo.Enabled = True
        Else
            '値ありの場合は工程（From,To）を無効化
            cmbProcCodeFrom.SelectedValue = ""
            cmbProcCodeTo.SelectedValue = ""
            cmbProcCodeFrom.Enabled = False
            cmbProcCodeTo.Enabled = False
        End If
    End Sub

    '工程入力処理
    Private Sub cmbProcCode_SelectChanged(sender As Object, e As EventArgs)
        If String.IsNullOrEmpty(cmbProcCode.SelectedValue) Then
            '値なしの場合は工程（From,To）を有効化
            cmbProcCodeFrom.Enabled = True
            cmbProcCodeTo.Enabled = True
        Else
            '値ありの場合は工程（From,To）を無効化
            cmbProcCodeFrom.SelectedValue = ""
            cmbProcCodeTo.SelectedValue = ""
            cmbProcCodeFrom.Enabled = False
            cmbProcCodeTo.Enabled = False
        End If
    End Sub

    '工程（From）入力処理手入力対応
    '工程（To）入力処理手入力対応
    Private Sub cmbProcCodeFromTo_TextChanged(sender As Object, e As EventArgs)
        If String.IsNullOrEmpty(cmbProcCodeFrom.Text) And String.IsNullOrEmpty(cmbProcCodeTo.Text) Then
            '値なしの場合は工程を有効化
            cmbProcCode.Enabled = True
        Else
            '値ありの場合は工程を無効化
            cmbProcCode.SelectedValue = ""
            cmbProcCode.Enabled = False
        End If
    End Sub

    '工程（From）入力処理
    '工程（To）入力処理
    Private Sub cmbProcCodeFromTo_SelectChanged(sender As Object, e As EventArgs)
        If String.IsNullOrEmpty(cmbProcCodeFrom.SelectedValue) And String.IsNullOrEmpty(cmbProcCodeTo.SelectedValue) Then
            '値なしの場合は工程を有効化
            cmbProcCode.Enabled = True
        Else
            '値ありの場合は工程を無効化
            cmbProcCode.SelectedValue = ""
            cmbProcCode.Enabled = False
        End If
    End Sub

    '入力チェック処理
    Private Function inputCheck()

        '工程の入力チェック
        Dim PerfectMatching As Integer = CInt(cmbProcCode.FindStringExact(cmbProcCode.Text))
        If PerfectMatching = -1 Then
            MsgBox(htMsgMst("MSG10047"))
            Return True
        Else
            cmbProcCode.SelectedValue = cmbProcCode.GetItemText(cmbProcCode.Items(PerfectMatching))
        End If

        Dim PerfectMatchingFrom As Integer = CInt(cmbProcCodeFrom.FindStringExact(cmbProcCodeFrom.Text))
        If PerfectMatchingFrom = -1 Then
            MsgBox(htMsgMst("MSG10047"))
            Return True
        Else
            cmbProcCodeFrom.SelectedValue = cmbProcCodeFrom.GetItemText(cmbProcCodeFrom.Items(PerfectMatchingFrom))
        End If

        Dim PerfectMatchingTo As Integer = CInt(cmbProcCodeTo.FindStringExact(cmbProcCodeTo.Text))
        If PerfectMatchingTo = -1 Then
            MsgBox(htMsgMst("MSG10047"))
            Return True
        Else
            cmbProcCodeTo.SelectedValue = cmbProcCodeTo.GetItemText(cmbProcCodeTo.Items(PerfectMatchingTo))
        End If


        '検索条件が日付指定のみの場合はエラーとする
        If String.IsNullOrEmpty(txtKeyNo.Text) And
            String.IsNullOrEmpty(txtWaferLotno.Text) And
            String.IsNullOrEmpty(txtShape.Text) And
            String.IsNullOrEmpty(cmbProcCode.SelectedValue) And
            String.IsNullOrEmpty(cmbProcCodeFrom.SelectedValue) And
            String.IsNullOrEmpty(cmbProcCodeTo.SelectedValue) And
            String.IsNullOrEmpty(txtEquipId.Text) And
            String.IsNullOrEmpty(txtPkg.Text) Then
            MsgBox(htMsgMst("MSG10043"))
            Return True
        End If

        '日付入力チェック
        If chkTime.Checked = True Then
            Dim FromString As String = DateTimePickerFrom.Text + " " + cmbHourFrom.SelectedValue + ":" + cmbMinuteFrom.SelectedValue + ":00"
            Dim ToString As String = DateTimePickerTo.Text + " " + cmbHourTo.SelectedValue + ":" + cmbMinuteTo.SelectedValue + ":59"
            Try
                FromDate = Date.Parse(FromString)
                ToDate = Date.Parse(ToString)

                If Date.Compare(FromDate, ToDate) = 1 Then
                    MsgBox(htMsgMst("MSG10044"))
                    Return True
                End If
            Catch ex As Exception
                Return True
            End Try
        End If

        '工程の入力チェック
        procFrom = cmbProcCodeFrom.FindStringExact(cmbProcCodeFrom.SelectedValue)
        procTo = cmbProcCodeTo.FindStringExact(cmbProcCodeTo.SelectedValue)
        If procFrom > procTo Then
            MsgBox(htMsgMst("MSG10045"))
            Return True
        End If

        '入力値大文字化
        txtKeyNo.Text = txtKeyNo.Text.ToUpper()
        txtWaferLotno.Text = txtWaferLotno.Text.ToUpper()
        txtShape.Text = txtShape.Text.ToUpper()
        txtEquipId.Text = txtEquipId.Text.ToUpper()
        txtPkg.Text = txtPkg.Text.ToUpper()

        Return False
    End Function

    '取消ボタン押下処理
    Private Sub Clear_Click(sender As Object, e As EventArgs) Handles btnClear.Click

        '検索条件欄初期化
        txtKeyNo.Text = String.Empty
        txtShape.Text = String.Empty
        cmbProcCode.SelectedValue = ""
        cmbProcCodeFrom.SelectedValue = ""
        cmbProcCodeTo.SelectedValue = ""
        txtEquipId.Text = String.Empty
        txtPkg.Text = String.Empty
        DateTimePickerFrom.Text = Today.ToString
        cmbHourFrom.SelectedValue = "0"
        cmbMinuteFrom.SelectedValue = "00"
        DateTimePickerTo.Text = Today.ToString
        cmbHourTo.SelectedValue = "23"
        cmbMinuteTo.SelectedValue = "59"
        chkTime.CheckState = CheckState.Unchecked


        '検索結果欄初期化
        DataGridView1.DataSource = Nothing
        '検索件数初期化
        txtRowCount.Text = ""
        isSerchResult = False

    End Sub

    'コンボボックスの選択肢設定
    Private Sub createComboBox()
        'コンボボックス（時）の設定
        Dim hourTableFrom As New DataTable()
        Dim hourTableTo As New DataTable()
        'DataTableに列を追加
        hourTableFrom.Columns.Add("ID", GetType(String))
        hourTableFrom.Columns.Add("NAME", GetType(String))
        hourTableTo.Columns.Add("ID", GetType(String))
        hourTableTo.Columns.Add("NAME", GetType(String))

        For i As Integer = 0 To 23
            '新しい行を作成
            Dim rowFrom As DataRow = hourTableFrom.NewRow()
            Dim rowTo As DataRow = hourTableTo.NewRow()
            '各列に値をセット
            rowFrom("ID") = i.ToString
            rowFrom("NAME") = i.ToString
            rowTo("ID") = i.ToString
            rowTo("NAME") = i.ToString
            'DataTableに行を追加
            hourTableFrom.Rows.Add(rowFrom)
            hourTableTo.Rows.Add(rowTo)
        Next

        hourTableFrom.AcceptChanges()
        hourTableTo.AcceptChanges()

        'コンボボックスのDataSourceにDataTableを割り当てる
        '月From
        cmbHourFrom.DataSource = hourTableFrom
        cmbHourFrom.DisplayMember = "NAME"
        cmbHourFrom.ValueMember = "ID"
        '月To
        cmbHourTo.DataSource = hourTableTo
        cmbHourTo.DisplayMember = "NAME"
        cmbHourTo.ValueMember = "ID"
        cmbHourTo.SelectedValue = "23"


        'コンボボックス（分）の設定
        Dim minuteTableFrom As New DataTable()
        Dim minuteTableTo As New DataTable()
        'DataTableに列を追加
        minuteTableFrom.Columns.Add("ID", GetType(String))
        minuteTableFrom.Columns.Add("NAME", GetType(String))
        minuteTableTo.Columns.Add("ID", GetType(String))
        minuteTableTo.Columns.Add("NAME", GetType(String))

        For i As Integer = 0 To 59
            '新しい行を作成
            Dim row As DataRow = minuteTableFrom.NewRow()
            Dim rowTo As DataRow = minuteTableTo.NewRow()
            '各列に値をセット
            row("ID") = String.Format("{0:D2}", i)
            row("NAME") = String.Format("{0:D2}", i)
            rowTo("ID") = String.Format("{0:D2}", i)
            rowTo("NAME") = String.Format("{0:D2}", i)
            'DataTableに行を追加
            minuteTableFrom.Rows.Add(row)
            minuteTableTo.Rows.Add(rowTo)
        Next

        minuteTableFrom.AcceptChanges()
        minuteTableTo.AcceptChanges()

        'コンボボックスのDataSourceにDataTableを割り当てる
        '月From
        cmbMinuteFrom.DataSource = minuteTableFrom
        cmbMinuteFrom.DisplayMember = "NAME"
        cmbMinuteFrom.ValueMember = "ID"
        '月To
        cmbMinuteTo.DataSource = minuteTableTo
        cmbMinuteTo.DisplayMember = "NAME"
        cmbMinuteTo.ValueMember = "ID"
        cmbMinuteTo.SelectedValue = "59"


        '工程コンボボックス作成
        'コンボボックス（時）の設定
        Dim procTable As New DataTable()
        Dim procTableFrom As New DataTable()
        Dim procTableTo As New DataTable()
        'DataTableに列を追加
        procTable.Columns.Add("ID", GetType(String))
        procTable.Columns.Add("NAME", GetType(String))
        procTableFrom.Columns.Add("ID", GetType(String))
        procTableFrom.Columns.Add("NAME", GetType(String))
        procTableTo.Columns.Add("ID", GetType(String))
        procTableTo.Columns.Add("NAME", GetType(String))

        '最初に空文字をセット
        Dim firstRow As DataRow = procTable.NewRow()
        '各列に値をセット
        firstRow("ID") = ""
        firstRow("NAME") = ""
        'DataTableに行を追加
        procTable.Rows.Add(firstRow)

        Dim firstRowFrom As DataRow = procTableFrom.NewRow()
        '各列に値をセット
        firstRowFrom("ID") = ""
        firstRowFrom("NAME") = ""
        procTableFrom.Rows.Add(firstRowFrom)

        Dim firstRowTo As DataRow = procTableTo.NewRow()
        '各列に値をセット
        firstRowTo("ID") = ""
        firstRowTo("NAME") = ""
        procTableTo.Rows.Add(firstRowTo)

        'DBから工程一覧取得
        Dim dtProcData = getProcData()

        If dtProcData.Rows.Count > 0 Then
            'セレクトボックスデータ作成
            For i As Integer = 0 To dtProcData.Rows.Count - 1
                '新しい行を作成
                Dim procRow As DataRow = procTable.NewRow()
                '各列に値をセット
                procRow("ID") = dtProcData.Rows(i)("proc_cd")
                procRow("NAME") = dtProcData.Rows(i)("proc_cd")
                'DataTableに行を追加
                procTable.Rows.Add(procRow)

                '新しい行を作成
                Dim procRowFrom As DataRow = procTableFrom.NewRow()
                '各列に値をセット
                procRowFrom("ID") = dtProcData.Rows(i)("proc_cd")
                procRowFrom("NAME") = dtProcData.Rows(i)("proc_cd")
                'DataTableに行を追加
                procTableFrom.Rows.Add(procRowFrom)

                '新しい行を作成
                Dim procRowTo As DataRow = procTableTo.NewRow()
                '各列に値をセット
                procRowTo("ID") = dtProcData.Rows(i)("proc_cd")
                procRowTo("NAME") = dtProcData.Rows(i)("proc_cd")
                'DataTableに行を追加
                procTableTo.Rows.Add(procRowTo)
            Next
        End If
        procTable.AcceptChanges()
        cmbProcCode.DataSource = procTable
        cmbProcCode.DisplayMember = "NAME"
        cmbProcCode.ValueMember = "ID"
        procTableFrom.AcceptChanges()
        cmbProcCodeFrom.DataSource = procTableFrom
        cmbProcCodeFrom.DisplayMember = "NAME"
        cmbProcCodeFrom.ValueMember = "ID"
        procTableTo.AcceptChanges()
        cmbProcCodeTo.DataSource = procTableTo
        cmbProcCodeTo.DisplayMember = "NAME"
        cmbProcCodeTo.ValueMember = "ID"

    End Sub

    '時間チェックボックス押下処理
    Private Sub chkTime_CheckedChanged(sender As Object, e As EventArgs) Handles chkTime.CheckedChanged

        If chkTime.Checked = True Then
            DateTimePickerFrom.Enabled = True
            cmbHourFrom.Enabled = True
            cmbMinuteFrom.Enabled = True
            DateTimePickerTo.Enabled = True
            cmbHourTo.Enabled = True
            cmbMinuteTo.Enabled = True
        Else
            DateTimePickerFrom.Enabled = False
            cmbHourFrom.Enabled = False
            cmbMinuteFrom.Enabled = False
            DateTimePickerTo.Enabled = False
            cmbHourTo.Enabled = False
            cmbMinuteTo.Enabled = False
        End If
    End Sub

    Private Sub serch()

        '事前に件数取得を行う。
        Dim dtCount As DataTable = getDataCount()
        Dim getCountInt As Integer = CInt(dtCount.Rows(0)("COUNT"))

        '検索条件値を超えているかチェックする
        If getCountInt = 0 Then
            '取得件数0件の場合は検索処理を終了する。
            txtRowCount.Text = 0
            isSerchResult = False
            MsgBox(htMsgMst("MSG10048"))
            Exit Sub
        ElseIf getCountInt > serchMaxCount Then
            '検索上限値を超えている場合は、メッセージを表示する。
            MsgBox(htMsgMst("MSG10046"))
            '取得件数に最大値を設定する。
            txtRowCount.Text = serchMaxCount
        Else
            '取得件数を設定する。
            txtRowCount.Text = getCountInt
        End If

        'l_lotdataよりデータを取得
        dtData = getData()
        If dtData.Rows.Count > 0 Then
            Me.DataGridView1.DataSource = dtData
            isSerchResult = True
        End If

    End Sub

    '工程コード一覧取得
    Private Function getProcData() As DataTable
        Dim szSql As String = ""
        szSql &= " SELECT proc_cd "
        szSql &= " FROM PER.t_proc_cd "
        szSql &= " ORDER BY flow_num "

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            getProcData = New DataTable
        Else
            getProcData = dt
        End If
    End Function

    '検索条件にヒットする件数を取得する。
    Private Function getDataCount() As DataTable
        Dim szSql As String = ""
        szSql &= "SELECT "
        szSql &= "  COUNT(*) COUNT " 'UPD MIAO 2018/10/30
        szSql &= "FROM "
        szSql &= "  ( "
        szSql &= "  SELECT  "
        szSql &= "      A.lot_no, "
        szSql &= "      B.komokudata, "
        szSql &= "      A.prod_name, "
        szSql &= "      A.koutei_cd, "
        szSql &= "      A.equip_id, "
        szSql &= "      A.type, "
        szSql &= "      A.opt_time, "
        szSql &= "      A.input_qty, "
        szSql &= "      A.complete_qty, "
        szSql &= "      A.defect_qty, "
        szSql &= "      A.inputfrm_qty, "
        szSql &= "      A.frame_qty, "
        szSql &= "      A.inputcross_qty, "
        szSql &= "      A.cross_qty, "
        szSql &= "      A.inputcross_frmqty, "
        szSql &= "      A.cross_frmqty "
        szSql &= "  FROM  "
        szSql &= "      MAT.l_sf_work_rslt_head AS A "
        szSql &= "  LEFT JOIN "
        szSql &= "      ( "
        szSql &= "       SELECT Z.klotno,Z.komokudata "
        szSql &= "       FROM per.l_jyokendata AS Z  "
        szSql &= "       WHERE Z.komokuname = 'AGGREGATE PKG' "
        szSql &= "      ) AS B "
        szSql &= "  ON "
        szSql &= "      A.lot_no = B.klotno "
        szSql &= "  WHERE  1=1" 'UPD MIAO 2018/10/30

        '組立Lot
        If Not String.IsNullOrEmpty(txtKeyNo.Text) Then
            szSql &= "  AND A.lot_no = '" + txtKeyNo.Text + "' "
        End If

        '品名
        If Not String.IsNullOrEmpty(txtShape.Text) Then
            szSql &= "  AND A.prod_name like '" + txtShape.Text + "%' "
        End If

        '工程
        If Not String.IsNullOrEmpty(cmbProcCode.SelectedValue) Then
            szSql &= "  AND A.koutei_cd = '" + cmbProcCode.SelectedValue + "' "
        End If

        '工程（期間）
        If Not cmbProcCodeFrom.SelectedValue = "" Then
            '工程の開始位置取得
            Dim sqlString As String = "("
            For i As Integer = procFrom To procTo

                If sqlString.Equals("(") Then
                    sqlString += "'" + cmbProcCodeFrom.GetItemText(cmbProcCodeFrom.Items(i)) + "'"
                Else
                    sqlString += " , "
                    sqlString += "'" + cmbProcCodeFrom.GetItemText(cmbProcCodeFrom.Items(i)) + "'"
                End If
            Next
            sqlString += " ) "
            szSql &= "  AND A.koutei_cd in " + sqlString
        End If

        '装置ID
        If Not String.IsNullOrEmpty(txtEquipId.Text) Then
            szSql &= " And A.equip_id = '" + txtEquipId.Text + "' "
        End If

        '集約PLG
        If Not String.IsNullOrEmpty(txtPkg.Text) Then
            szSql &= "  AND A.shape = '" + txtPkg.Text + "' "
        End If

        '時間
        If chkTime.Checked = True Then
            szSql &= "  AND A.opt_time between timestamp '" + FromDate + "' and timestamp   '" + ToDate + "' "
        End If

        szSql &= "  ) AS C "
        szSql &= "INNER JOIN  "
        szSql &= "  PER.l_tag_lotdata AS D "
        szSql &= "ON C.lot_no = D.lot_no "

        'GroupKeyNo
        If Not String.IsNullOrEmpty(txtWaferLotno.Text) Then
            szSql &= "  WHERE  "
            szSql &= "    D.wafer_lotno = '" + txtWaferLotno.Text + "' "
        End If

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            getDataCount = New DataTable
        Else
            getDataCount = dt
        End If
    End Function

    '検索条件にヒットするデータを取得する。
    Private Function getData() As DataTable
        Dim szSql As String = ""
        szSql &= "SELECT "
        szSql &= "  D.wafer_lotno, "
        szSql &= "  C.lot_no, "
        szSql &= "  C.komokudata AS pkg,"
        szSql &= "  C.prod_name, "
        szSql &= "  C.koutei_cd, "
        szSql &= "  C.equip_id, "
        szSql &= "  CASE WHEN C.type = '1' THEN '" + htMsgMst("MSG10040") + "' "
        szSql &= "       WHEN C.type = '2' THEN '" + htMsgMst("MSG10041") + "' "
        szSql &= "       WHEN C.type = '3' THEN '" + htMsgMst("MSG10042") + "' "
        szSql &= "       WHEN C.type = '9' THEN '" + htMsgMst("MSG00122") + "' " 'ADD MIAO 2018/8/14
        szSql &= "  END AS status, "
        szSql &= "  C.opt_time, "
        szSql &= "  '' AS Rack1, "
        szSql &= "  '' AS Rack2, "
        szSql &= "  '' AS Rack3, "
        szSql &= "  '' AS Rack4, "
        szSql &= "  '' AS Rack5, "
        szSql &= "  C.input_qty, "
        szSql &= "  C.complete_qty, "
        szSql &= "  C.defect_qty, "
        szSql &= "  C.inputfrm_qty, "
        szSql &= "  C.frame_qty, "
        szSql &= "  C.inputcross_qty, "
        szSql &= "  C.cross_qty, "
        szSql &= "  C.inputcross_frmqty, "
        szSql &= "  C.cross_frmqty "
        szSql &= "FROM "
        szSql &= "  ( "
        szSql &= "  SELECT  "
        szSql &= "      A.lot_no, "
        szSql &= "      B.komokudata, "
        szSql &= "      A.prod_name, "
        szSql &= "      A.koutei_cd, "
        szSql &= "      A.equip_id, "
        szSql &= "      A.type, "
        szSql &= "      A.opt_time, "
        szSql &= "      A.input_qty, "
        szSql &= "      A.complete_qty, "
        szSql &= "      A.defect_qty, "
        szSql &= "      A.inputfrm_qty, "
        szSql &= "      A.frame_qty, "
        szSql &= "      A.inputcross_qty, "
        szSql &= "      A.cross_qty, "
        szSql &= "      A.inputcross_frmqty, "
        szSql &= "      A.cross_frmqty "
        szSql &= "  FROM  "
        szSql &= "      MAT.l_sf_work_rslt_head AS A "
        szSql &= "  LEFT JOIN "
        szSql &= "      ( "
        szSql &= "       SELECT Z.klotno,Z.komokudata "
        szSql &= "       FROM per.l_jyokendata AS Z  "
        szSql &= "       WHERE Z.komokuname = 'AGGREGATE PKG' "
        szSql &= "      ) AS B "
        szSql &= "  ON "
        szSql &= "      A.lot_no = B.klotno "
        szSql &= "  WHERE  1=1 " 'UPD MIAO 2018/10/30

        '組立Lot
        If Not String.IsNullOrEmpty(txtKeyNo.Text) Then
            szSql &= "  AND A.lot_no = '" + txtKeyNo.Text + "' "
        End If

        '品名
        If Not String.IsNullOrEmpty(txtShape.Text) Then
            szSql &= "  AND A.prod_name like '" + txtShape.Text + "%' "
        End If

        '工程
        If Not String.IsNullOrEmpty(cmbProcCode.SelectedValue) Then
            szSql &= "  AND A.koutei_cd = '" + cmbProcCode.SelectedValue + "' "
        End If

        '工程（期間）
        If Not cmbProcCodeFrom.SelectedValue = "" Then
            '工程の開始位置取得
            Dim sqlString As String = "("
            For i As Integer = procFrom To procTo

                If sqlString.Equals("(") Then
                    sqlString += "'" + cmbProcCodeFrom.GetItemText(cmbProcCodeFrom.Items(i)) + "'"
                Else
                    sqlString += " , "
                    sqlString += "'" + cmbProcCodeFrom.GetItemText(cmbProcCodeFrom.Items(i)) + "'"
                End If
            Next
            sqlString += " ) "
            szSql &= "  AND A.koutei_cd in " + sqlString
        End If

        '装置ID
        If Not String.IsNullOrEmpty(txtEquipId.Text) Then
            szSql &= " And A.equip_id = '" + txtEquipId.Text + "' "
        End If

        '集約PLG
        If Not String.IsNullOrEmpty(txtPkg.Text) Then
            szSql &= "  AND A.shape = '" + txtPkg.Text + "' "
        End If

        '時間
        If chkTime.Checked = True Then
            szSql &= "  AND A.opt_time between timestamp '" + FromDate + "' and timestamp   '" + ToDate + "' "
        End If

        szSql &= "  ) AS C "
        szSql &= "INNER JOIN  "
        szSql &= "  PER.l_tag_lotdata AS D "
        szSql &= "ON C.lot_no = D.lot_no "

        'GroupKeyNo
        If Not String.IsNullOrEmpty(txtWaferLotno.Text) Then
            szSql &= "  WHERE  "
            szSql &= "    D.wafer_lotno = '" + txtWaferLotno.Text + "' "
        End If

        szSql &= "ORDER BY "
        szSql &= "  D.wafer_lotno, C.lot_no, C.opt_time "
        szSql &= "Limit " + serchMaxCount.ToString

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            getData = New DataTable
        Else
            getData = dt
        End If
    End Function

    'DataGridviewダブルクリック処理
    Private Sub dataGridView1_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick

        '検索が成功している場合のみ子画面を開く
        If isSerchResult Then
            '選択行数取得
            Dim selectRow As Integer = DataGridView1.CurrentCell.RowIndex

            If selectRow = CInt(txtRowCount.Text) Then
                '最後の空行選択時は終了する。
                Exit Sub
            End If

            Dim frmHistryDetails As New frmHistoryDetails()
            '子画面に値を渡す
            frmHistryDetails.wafer_lotno = DataGridView1.Item(0, selectRow).Value
            frmHistryDetails.lot_no = DataGridView1.Item(1, selectRow).Value
            frmHistryDetails.procCd = DataGridView1.Item(4, selectRow).Value
            frmHistryDetails.opt_time = DataGridView1.Item(7, selectRow).Value
            frmHistryDetails.status = DataGridView1.Item(6, selectRow).Value
            frmHistryDetails.StartPosition = FormStartPosition.CenterParent
            '子画面を開く
            frmHistryDetails.ShowDialog()
        End If
    End Sub

    'DataGridViewの設定
    Private Sub settingGridView()
        'ヘッダーの自動生成不可
        '設定しないと検索結果を削除した際に、ヘッダーも削除される。
        DataGridView1.AutoGenerateColumns = False
    End Sub

    'DBから最大検索数を取得する。
    Private Sub getSerchMaxCount()
        Dim szSql As String = ""
        szSql &= " SELECT "
        szSql &= "     num_param1 "
        szSql &= " FROM "
        szSql &= "     KAD.t_factory_info "
        szSql &= " WHERE "
        szSql &= "     param_id = '9998' "

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        'DBに最大取得件数が設定されている場合は、取得件数を更新する。
        If Not IsNothing(dt) Then
            Try
                Dim intCount As Integer = CInt(dt.Rows(0)("num_param1"))
                'DB登録値が1以上の場合は検索上限値に設定する。
                If intCount > 1 Then
                    serchMaxCount = CInt(dt.Rows(0)("num_param1"))
                End If
            Catch ex As Exception
                '数値変換できない場合はデフォルト値を使用する。
            End Try
        End If

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCsvOutput.Click
        'SaveFileDialogクラスのインスタンスを作成
        Dim sfd As New SaveFileDialog()

        sfd.FileName = fileName
        'はじめに表示されるフォルダを指定する
        '指定しない（空の文字列）の時は、現在のディレクトリが表示される
        sfd.InitialDirectory = "C:\"
        '[ファイルの種類]に表示される選択肢を指定する
        sfd.Filter = "すべてのファイル(*.*)|*.*"
        '[ファイルの種類]ではじめに選択されるものを指定する
        '2番目の「すべてのファイル」が選択されているようにする
        sfd.FilterIndex = 1
        'タイトルを設定する
        sfd.Title = fileSaveTitle
        'ダイアログボックスを閉じる前に現在のディレクトリを復元するようにする
        sfd.RestoreDirectory = True
        '既に存在するファイル名を指定したとき警告する
        'デフォルトでTrueなので指定する必要はない
        sfd.OverwritePrompt = True
        '存在しないパスが指定されたとき警告を表示する
        'デフォルトでTrueなので指定する必要はない
        sfd.CheckPathExists = True

        'ダイアログを表示する
        'UPD MIAO 2018/8/14 BEGIN
        If sfd.ShowDialog() = DialogResult.OK Then
            'OKボタンがクリックされたとき、CSVファイル作成を行う。
            If createCSV(sfd.FileName & ".csv") Then

                MsgBox(getMsgStr("MSG00047"))

            Else
                MsgBox(getMsgStr("MSG10022"))
            End If
        End If
        'UPD MIAO 2018/8/14 END

    End Sub
    'ADD ADD MIAO 2018/8/14 BEGIN
    Private Function createCSV(ByVal filePath As String) As Boolean
        Try
            Dim mFileContent As String = ""

            For index = 0 To DataGridView1.ColumnCount - 1
                If index = 0 Then
                    mFileContent = DataGridView1.Columns(index).HeaderText

                Else
                    mFileContent = mFileContent & "," & DataGridView1.Columns(index).HeaderText
                End If
            Next
            mFileContent = mFileContent & vbCrLf
            For Each row As DataGridViewRow In DataGridView1.Rows

                For index = 0 To DataGridView1.ColumnCount - 1
                    Dim mFieldValue As String


                    If String.IsNullOrEmpty（row.Cells(index).Value.ToString） Then
                        mFieldValue = ""
                    Else
                        mFieldValue = row.Cells(index).Value.ToString
                    End If


                    If index = 0 Then
                        mFileContent = mFileContent & mFieldValue

                    Else
                        mFileContent = mFileContent & "," & mFieldValue
                    End If

                Next
                mFileContent = mFileContent & vbCrLf
            Next
            My.Computer.FileSystem.WriteAllBytes(filePath, System.Text.Encoding.Default.GetBytes(mFileContent), False)

            Return True

        Catch ex As Exception

            Return False

        End Try
    End Function
    'ADD ADD MIAO 2018/8/14 END
    'ADD MIAO 2018/10/17 Begin
    Public Function DBNullTOblank(obj As Object) As String
        DBNullTOblank = IIf(IsDBNull(obj), "", obj)
    End Function
    'ADD MIAO 2018/10/17 END
End Class